import { NextRequest, NextResponse } from 'next/server';
import { query } from '@/lib/mysql';
import { getCurrentUser } from '@/lib/auth';

export async function POST(request: NextRequest) {
  try {
    // 验证用户身份
    const user = getCurrentUser();
    if (!user) {
      return NextResponse.json(
        { success: false, error: '请先登录' },
        { status: 401 }
      );
    }

    // 解析请求体
    const body = await request.json();
    const { topicId } = body;

    if (!topicId) {
      return NextResponse.json(
        { success: false, error: '缺少topicId参数' },
        { status: 400 }
      );
    }

    // 获取topic_name（从topicId推断）
    const topicName = topicId.replace(/-/g, ' ').replace(/\b\w/g, (l: string) => l.toUpperCase());

    // 更新或插入学习进度
    await query(
      `INSERT INTO user_progress (user_id, topic_id, topic_name, is_learned, updated_at)
       VALUES (?, ?, ?, TRUE, NOW())
       ON DUPLICATE KEY UPDATE is_learned = TRUE, updated_at = NOW()`,
      [user.userId, topicId, topicName]
    );

    return NextResponse.json({
      success: true,
      message: '已标记为学会'
    });

  } catch (error) {
    console.error('标记已学会错误:', error);
    return NextResponse.json(
      { 
        success: false, 
        error: error instanceof Error ? error.message : '操作失败' 
      },
      { status: 500 }
    );
  }
}

